# -*- coding: utf-8 -*-
import os

from flask import Flask, render_template, request
# import tensorflow.compat.v1 as tf
# tf.disable_v2_behavior()
# tf.compat.v1.disable_eager_execution()

import numpy as np
import cv2
from tensorflow import keras

app = Flask(__name__)

height = 128
width = 128
channel = 3
batch_size = 64
valid_batch_size = 64
num_classes = 2
epochs = 2


logdir = './graph_def_and_weights'
output_model_file = os.path.join(logdir,"catDog_weights.h5")


model = keras.models.Sequential([
        keras.layers.Conv2D(filters=32, kernel_size=3,
                            padding='same', activation='relu',
                            input_shape=[width, height, channel]),
        keras.layers.Conv2D(filters=32, kernel_size=3,
                            padding='same', activation='relu'),
        keras.layers.MaxPool2D(pool_size=2),

        keras.layers.Conv2D(filters=64, kernel_size=3,
                            padding='same', activation='relu'),
        keras.layers.Conv2D(filters=64, kernel_size=3,
                            padding='same', activation='relu'),
        keras.layers.MaxPool2D(pool_size=2),

        keras.layers.Conv2D(filters=128, kernel_size=3,
                            padding='same', activation='relu'),
        keras.layers.Conv2D(filters=128, kernel_size=3,
                            padding='same', activation='relu'),
        keras.layers.MaxPool2D(pool_size=2),

        keras.layers.Flatten(),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(num_classes, activation='softmax')
    ])

model.compile(loss='categorical_crossentropy',
              optimizer='adam', metrics=['accuracy'])
model.summary()


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/Identifycatanddog', methods=['POST'])

def predict():
    # 从 POST 请求中获取图片数据
    image_data = request.files['file'].read()
    imgtext = request.files['file'].filename
    # turetext = turetext.split("_")[0][:4]
    # 将图片数据解码为 Numpy 数组
    image_array = np.frombuffer(image_data, np.uint8)
    img = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    img = cv2.resize(img, (128, 128))

    # load the weights of model
    model.load_weights(output_model_file)

    os.makedirs('./save', exist_ok=True)
    os.makedirs('./save/cat', exist_ok=True)
    os.makedirs('./save/dog', exist_ok=True)

    i = 1
    img_arr = img / 255.0
    img_arr = img_arr.reshape((1, width, height, 3))
    pre = model.predict(img_arr)
    if pre[0][0] > pre[0][1]:
        cv2.imwrite('./save/cat/' + '{}.jpg'.format(i), img)
        predict_message = '猫！'
        print(imgtext, ' is classified as Cat.')
    else:
        cv2.imwrite('./save/dog/' + '{}.jpg'.format(i), img)
        predict_message = '狗！'
        print(imgtext, ' is classified as Dog.')
    i = i + 1
    return {
        "predict_message":predict_message
    }
    # return image

if __name__ == '__main__':
    app.run(debug=True)